import { Footer } from "@/components"
import {
  AlipayCircleOutlined,
  LockOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined
} from "@ant-design/icons"
import { LoginForm, ProFormText } from "@ant-design/pro-components"
import {
  FormattedMessage,
  Helmet,
  history,
  SelectLang,
  useIntl,
  useModel
} from "@umijs/max"
import { Alert, App, Tabs } from "antd"
import { createStyles } from "antd-style"
import React, { useState } from "react"
import { flushSync } from "react-dom"
import Settings from "../../../../config/defaultSettings"

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: "8px",
      color: "rgba(0, 0, 0, 0.2)",
      fontSize: "24px",
      verticalAlign: "middle",
      cursor: "pointer",
      transition: "color 0.3s",
      "&:hover": {
        color: token.colorPrimaryActive
      }
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: "42px",
      position: "fixed",
      right: 16,
      borderRadius: token.borderRadius,
      ":hover": {
        backgroundColor: token.colorBgTextHover
      }
    },
    container: {
      display: "flex",
      flexDirection: "column",
      height: "100vh",
      overflow: "auto",
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: "100% 100%"
    }
  }
})

const ActionIcons = () => {
  const { styles } = useStyles()

  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  )
}

const Lang = () => {
  const { styles } = useStyles()

  return (
    <div className={styles.lang} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  )
}

const LoginMessage: React.FC<{
  content: string
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24
      }}
      message={content}
      type="error"
      showIcon
    />
  )
}

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({})
  const [type, setType] = useState<string>("account")
  const { initialState, setInitialState } = useModel("@@initialState")
  const { styles } = useStyles()
  const intl = useIntl()
  const { message } = App.useApp()
  const { callPy } = useModel("websocketModel")
  const { updateProduceData } = useModel("produceModel")

  const fetchUserInfo = async (msg: any, values: any) => {
    const userInfo = {
      name: values.username,
      access: msg.currentAuthority,
      avatar: "./avatar.png"
    }
    if (userInfo) {
      flushSync(() => {
        // 保存到本地,然后刷新的时候可以直接使用
        localStorage.setItem("currentUser", JSON.stringify(userInfo))
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo
        }))
      })
    }
  }

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = (await callPy("um", "login_from_web", [
        { ...values }
      ])) as API.LoginResult
      if (msg.status === "ok") {
        setUserLoginState(msg)
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: "pages.login.success",
          defaultMessage: "登录成功！"
        })
        message.success(defaultLoginSuccessMessage)
        await fetchUserInfo(msg, { ...values })
        history.push("/produce")
        const response = await callPy("db", "get_order_show_from_web", [])
        if (!response.state) {
          message.error(response.info)
        }
        {
          updateProduceData({ workingOrder: response.data })
        }
        return
      }
      message.error(msg.info) // 登录失败,通过info显示失败信息
      console.log(msg)
      // 如果失败去设置用户错误信息
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: "pages.login.failure",
        defaultMessage: "登录失败，请重试！"
      })
      console.log(error)
      message.error(defaultLoginFailureMessage)
    }
  }
  const { status } = userLoginState

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: "menu.login",
            defaultMessage: "登录页"
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: "1",
          padding: "32px 0"
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: "75vw"
          }}
          logo={<img alt="logo" src="/logo.png" style={{ width: 80, height: "auto" }} />}
          title={
            <span style={{ marginLeft: 30, fontSize: 22 }}>
              {intl.formatMessage({ id: "login.title" })}
            </span>
          }
          subTitle={
            <span style={{ fontSize: 16 }}>
              {intl.formatMessage({ id: "login.subTitle" })}
            </span>
          }
          initialValues={{
            autoLogin: true
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams)
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: "account",
                label: intl.formatMessage({
                  id: "pages.login.accountLogin.tab",
                  defaultMessage: "账户密码登录"
                })
              }
            ]}
          />

          {status === "error" && (
            <LoginMessage
              content={intl.formatMessage({
                id: "pages.login.accountLogin.errorMessage",
                defaultMessage: "账户或密码错误(admin/ant.design)"
              })}
            />
          )}
          {type === "account" && (
            <>
              <ProFormText
                initialValue="user"
                name="username"
                fieldProps={{
                  size: "large",
                  prefix: <UserOutlined />
                }}
                placeholder={intl.formatMessage({
                  id: "pages.login.username.placeholder",
                  defaultMessage: "用户名: admin or user"
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    )
                  }
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: "large",
                  prefix: <LockOutlined />
                }}
                placeholder={intl.formatMessage({
                  id: "pages.login.password.placeholder"
                })}
                rules={[
                  {
                    required: true,
                    message: <FormattedMessage id="pages.login.password.required" />
                  }
                ]}
              />
            </>
          )}
        </LoginForm>
      </div>
      <Footer />
    </div>
  )
}

export default () => (
  <App>
    <Login />
  </App>
)
